import { useEffect, useMemo } from "react";
import { debounce, isFunction } from "lodash-es";

const useTimeOut = (fn: () => void, delay = 200) => {
	useEffect(() => {
		const timer = window.setTimeout(() => {
			fn();
		}, delay);
		return () => {
			window.clearTimeout(timer);
		};
	}, [delay, fn]);
};

const useInterval = (fn: () => void, delay = 200) => {
	useEffect(() => {
		const timer = window.setInterval(() => {
			fn();
		}, delay);
		return () => {
			window.clearInterval(timer);
		};
	}, [delay, fn]);
};
type noop = (...args: any[]) => any;
const useDebounce = <T extends noop>(fn: T, wait = 200) => {
	if (!isFunction(fn)) {
		console.error("useDebounce: fn must be a function");
	}
	return useMemo(
		() =>
			debounce((...args) => {
				fn(...args);
			}, wait),
		[fn, wait]
	);
};

export { useTimeOut, useInterval, useDebounce };
